package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.entity.DutyScheduleInfo;
import com.hzeport.bgs22emduty.entity.ParamScheduleSetting;
import com.hzeport.bgs22emduty.entity.ParamSubsidy;
import com.hzeport.bgs22emduty.enums.DTypeEnum;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.DutyScheduleInfoRepository;
import com.hzeport.bgs22emduty.outbound.ParamDutyRepository;
import com.hzeport.bgs22emduty.outbound.ParamScheduleSettingRepository;
import com.hzeport.bgs22emduty.vo.ParamDuty.ParamDutyListVO;
import com.hzeport.bgs22emduty.vo.ParamDuty.ParamDutySaveVO;
import com.hzeport.bgs22emduty.vo.base.PageVO;
import com.hzeport.bgs22emduty.common.base.BaseEntity;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.entity.ParamDuty;
import com.hzeport.bgs22emduty.outbound.db.ParamDutyRepositoryImpl;
import com.hzeport.bgs22emduty.service.ParamDutyService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 参数表-值班配置表：
此表中存储，各部门值班的参数配置
 *
 * @author code generator
 * @date 2022-12-02 11:21:59
 */
@Service
@Slf4j
public class ParamDutyServiceImpl extends BaseServiceImpl<ParamDutyRepositoryImpl, ParamDuty> implements ParamDutyService {

    @Resource
    private ParamDutyRepository paramDutyRepository;

    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private ParamScheduleSettingRepository paramScheduleSettingRepository;

    @Override
    public BaseResult<Page<ParamDutyListVO>> list(PageVO pageVO,UserInfoDetailVO userInfoDetailVO) {
            Page<ParamDuty>  page=new Page<>();
//            if (userInfoDetailVO.getRole()!=null&&userInfoDetailVO.getRole().contains("SYSTEM_ADMIN")){
//                page=paramDutyRepository.page(new Page<>(pageVO.getPageNum(),pageVO.getPageSize()),
//                        new LambdaQueryWrapper<ParamDuty>().orderByDesc(BaseEntity::getCreateTime));
//            }else {
                String custom=userInfoDetailVO.getCustomscode();
                page=paramDutyRepository.page(new Page<>(pageVO.getPageNum(),pageVO.getPageSize()),
                        new LambdaQueryWrapper<ParamDuty>().eq(ParamDuty::getDDept,custom).orderByDesc(BaseEntity::getCreateTime));
//            }
            List<ParamDutyListVO> listvo=page.getRecords().stream().map(i->{
            ParamDutyListVO paramDutyListVO = new ParamDutyListVO();
                BeanUtils.copyProperties(i,paramDutyListVO);
                paramDutyListVO.setSTime(i.getDStartTime()+"-"+i.getDEndTime());
               return paramDutyListVO;
            }).collect(Collectors.toList());
            Page<ParamDutyListVO> pageIno=new Page();
            pageIno.setRecords(listvo);
            pageIno.setTotal(page.getTotal());
            return BaseResult.ok(pageIno,"查询成功");
    }

    @Override
    public BaseResult delete(String id, UserInfoDetailVO userInfoDetailVO) throws Exception{

        // 排版配置删除
        int count=dutyScheduleInfoRepository.count(new LambdaQueryWrapper<DutyScheduleInfo>()
        .eq(DutyScheduleInfo::getDutyTimesId,id));
        if (count>0){
            throw new Exception("已经进行过排班的排班时段不能删除");
        }
        paramScheduleSettingRepository.remove( new LambdaQueryWrapper< ParamScheduleSetting >().eq( ParamScheduleSetting::getParamDutyId , id ) );
        // 时段删除
        paramDutyRepository.remove( new LambdaQueryWrapper< ParamDuty >().eq( ParamDuty::getId , id ) );
        return BaseResult.ok(null,"删除成功");
    }

    @Override
    public BaseResult<ParamDutyListVO> detail(String id) {
        ParamDuty holidays = paramDutyRepository.getById(id);
        ParamDutyListVO paramDutyListVO = new ParamDutyListVO();
        BeanUtils.copyProperties(holidays,paramDutyListVO);
        return BaseResult.ok(paramDutyListVO,"详情获取成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveData(ParamDutySaveVO paramDutySaveVO, UserInfoDetailVO userInfoDetailVO) throws Exception {
        if(StringUtils.isEmpty(paramDutySaveVO.getDDept())){
            throw new Exception("关区不能为空！");
        }
        if(StringUtils.isEmpty(paramDutySaveVO.getDType())){
            throw new Exception("值班类型不能为空！");
        }
        if(StringUtils.isEmpty(paramDutySaveVO.getStartTime())){
            throw new Exception("起始时间不能为空！");
        }
        if(StringUtils.isEmpty(paramDutySaveVO.getEndTime())){
            throw new Exception("结束时间不能为空！");
        }
        ParamDuty paramDuty = new ParamDuty();
        BeanUtils.copyProperties(paramDutySaveVO,paramDuty);
        paramDuty.setDStartTime(LocalTime.parse(paramDutySaveVO.getStartTime()));
        paramDuty.setDEndTime(LocalTime.parse(paramDutySaveVO.getEndTime()));
        LambdaUpdateWrapper<ParamDuty> countLambda=new LambdaUpdateWrapper<ParamDuty>()
                .eq(ParamDuty::getDDept,paramDutySaveVO.getDDept())
                .eq(ParamDuty::getDType,paramDutySaveVO.getDType());
        if (!org.apache.commons.lang.StringUtils.isEmpty(paramDutySaveVO.getId())){
            countLambda.ne(ParamDuty::getId,paramDutySaveVO.getId());
        }
        int count=repository.count(countLambda);
        if (count>0){
            throw new Exception("同一关区同一值班时段只能配置一份");
        }
        if(StringUtils.isEmpty(paramDuty.getId())){
            paramDuty.setCreateBy(userInfoDetailVO.getUserId());
            paramDuty.setCreateTime(LocalDateTime.now());
            paramDuty.setUpdateBy(userInfoDetailVO.getUserId());
            paramDuty.setUpdateTime(LocalDateTime.now());
            paramDuty.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            boolean b = paramDutyRepository.save(paramDuty);
        }else {
            ParamDuty byId = paramDutyRepository.getById(paramDuty.getId());
            paramDuty.setUpdateBy(userInfoDetailVO.getUserId());
            paramDuty.setUpdateTime(LocalDateTime.now());
            paramDuty.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            if (byId != null){
                paramDuty.setRecVersion(byId.getRecVersion());
            }
            boolean b = paramDutyRepository.updateById(paramDuty);
        }
        // 将该关区下大于此值班时段的start和end 时间都改掉
        List< DutyScheduleInfo > scheduleInfos = dutyScheduleInfoRepository.list( new LambdaQueryWrapper< DutyScheduleInfo >()
                .eq( DutyScheduleInfo::getCustomId , paramDutySaveVO.getDDept() )
                .ge( DutyScheduleInfo::getDDay , LocalDate.now() )
                .eq( DutyScheduleInfo::getDutyTimesId , paramDuty.getId() )
        );
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "HH:mm" );
        scheduleInfos.stream().map( item -> {
            item.setDStartDateTime( LocalDateTime.of( item.getDDay() ,  paramDuty.getDStartTime()) );
            item.setDEndDateTime(LocalDateTime.of( item.getDDay() ,  paramDuty.getDEndTime()) );
            item.setDutyTimesString( DTypeEnum.getDescByCode( paramDutySaveVO.getDType() ) + "(" + paramDuty.getDStartTime().format( formatter ) +"~"+ paramDuty.getDEndTime().format( formatter ) + ")" );
            return item;
        } ).collect( Collectors.toList());
        dutyScheduleInfoRepository.updateBatchById( scheduleInfos );
        return BaseResult.ok(paramDuty,"保存成功");
    }

    @Override
    public BaseResult<List<ParamDuty>> listTime(String id) {
        List<ParamDuty> list=paramDutyRepository.list(new LambdaQueryWrapper<ParamDuty>()
        .eq(ParamDuty::getDDept,id));
        return BaseResult.ok(list,"获取成功");
    }

    @Override
    public BaseResult< String > ifRemove( String id ) {
        List< ParamScheduleSetting > settingList = paramScheduleSettingRepository.list( new LambdaQueryWrapper< ParamScheduleSetting >()
                .eq( ParamScheduleSetting::getParamDutyId , id ) );
        if ( CollectionUtils.isEmpty( settingList ) ) {
            return BaseResult.ok("1");
        }
        return BaseResult.ok("0","该时段在排班配置页面被使用，您确定要删除吗？");
    }
}
